/**
 * Copyright(c) 2025 hbswxx.com, All Rights Reserved. Author: kouqiang Create date: 2025/5/30
 */
package cn.sw.syncdata.util;

import java.time.Duration;
import java.time.LocalDateTime;
import java.util.Random;

/**
 * description:
 *
 * @author kouqiang
 * @date 2025/5/30 13:29
 */
public class Util {
    private static final Random RANDOM = new Random();

/***
 * description:  在[start, end]区间内随机生成一个LocalDateTime
 * @author kouqiang
 * @date 2025/5/30 13:37
 * @param start
 * @param end
 * @return: java.time.LocalDateTime
 */

    public static LocalDateTime randomBetween(LocalDateTime start, LocalDateTime end) {

        if (start.isAfter(end)) {
            throw new IllegalArgumentException("start time must be before or equal to end time");
        }
        LocalDateTime startSec = start.withNano(0);
        LocalDateTime endSec = end.withNano(0);
        long secDiff = Duration.between(startSec, endSec).getSeconds();

        // 使用nextLong()生成0到secDiff的随机数（处理大数情况）
        long randomSec;
        if (secDiff <= 0) {
            randomSec = 0;
        } else {
            randomSec = Math.abs(RANDOM.nextLong()) % (secDiff + 1);
        }
        LocalDateTime randomTime = startSec.plusSeconds(randomSec);
        return randomTime.isAfter(endSec) ? endSec : randomTime;
    }
}
